#include "networking.h"

using namespace std;
/*
 * The first approach, assumes the server and client talk alternatively
 * Example:  Try on an smtp server %client1 -h mr1.its.yale.edu -p 25 -d
 */

int      debug=0;
uint16_t serverport=21;
char     *hostname=NULL;

static void
parse_args(int argc, char** argv) 
{
  int n = 1;
  while (n < argc) {
    if (strcmp(argv[n], "-h") == 0) {
      hostname = argv[++n];
    } else if (strcmp(argv[n], "-d") == 0) {
      debug = 1;
    } else if (strcmp(argv[n], "-p") == 0) {
      serverport = atoi(argv[++n]);
    } else
      err_quit("usage: %s [-h <hostname>] [-p <port>] [-d]", argv[0]);
    n++;
  }
  if (hostname == NULL)
    err_quit("usage: %s [-h <hostname>] [-p <port>] [-d]", argv[0]);
}

int
main(int argc, char **argv)
{
  int				sockfd;
  struct sockaddr_in	        servaddr;
  struct in_addr		**pptr;
  struct hostent		*hp;

  parse_args(argc, argv);

  // create a socket
  if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    err_quit("Cannot creat socket!");
  }
  
  // get server address
  if ( (hp = gethostbyname(hostname)) == NULL) {
    err_quit("Cannot resovle hostname!");
  }

  // parse the addresses
  pptr = (struct in_addr **) hp->h_addr_list;
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(serverport);
  memcpy(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
  char charname[MAXLINE];
  if (debug) cerr << "Connect to server " << inet_ntop(AF_INET, &servaddr.sin_addr, charname, sizeof(charname)) << endl;
    
  // connect to the server
  if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0) {
    close(sockfd);
    err_quit("Cannot connect to server!");
  }

  // start the loop
  char	sendline[MAXLINE], recvline[MAXLINE + 1];
  socketstream ss(sockfd);
  
  while (fgets(sendline, sizeof(sendline), stdin)) {
	  ss.writen_socket(sendline, strlen(sendline));

	  if (ss.read_line(recvline, MAXLINE) > 0)
		  fprintf(stdout, "%s\n", recvline);
  }
  // First read from server (e.g. from the remote side)
  /*
  while  (ss.read_line(recvline, MAXLINE) > 0) {
    fprintf(stdout, "%s", recvline);
    // Next get a command from the local user
    if (fgets(sendline, sizeof(sendline), stdin))
      ss.writen_socket(sendline, strlen(sendline));
    else
      exit(0);
  }
  */
}
